<template>
  <div class="app_login">
    <el-card shadow="hover">
      <template #header>
        <h3>锋购后台管理系统</h3>
      </template>
      <el-form ref="ruleFormRef" :model="loginForm" status-icon :rules="rules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密&nbsp;&nbsp;&nbsp;&nbsp;码" prop="password">
          <el-input v-model="loginForm.password" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm()">登录</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus';
import { loginRequest } from '@/api/userApi';

export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          {
            required: true,
            trigger: "blur",
            validator: function (rule, value, callback) {
              console.log(rule, value);
              const reg = /^\w{5,}$/;
              if (!reg.test(value)) {
                callback(new Error("用户名至少是5位数字字母下划线"));
              } else {
                callback();
              }
            },
          },
        ],
        password: [
          {
            required: true,
            validator: function (rule, value, callback) {
              console.log(rule, value);
              const reg = /^\w{5,}$/;

              if (!reg.test(value)) {
                callback(new Error("密码至少是5位数字字母下划线"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    console.log(this.$refs.ruleFormRef);
    console.log("mounted");
  },
  methods: {
    resetForm() {
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.resetFields();
        console.log("resetForm");
      } else {
        console.error("表单引用不存在");
      }
    },
    submitForm() {
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.validate((valid) => {
          if (valid) {
            console.log("submit!");
            console.log(this.loginForm);

            // 发起登录请求
            loginRequest(this.loginForm.username, this.loginForm.password)
              .then(response => {
                console.log('登录响应:', response.data);

                // 检查响应状态
                if (response.data.code === '200') {
                  // 登录成功，存储token
                  localStorage.setItem('token', response.data.data.token);
                  localStorage.setItem('adminname', response.data.data.adminname);

                  // 显示成功消息
                  ElMessage({
                    showClose: true,
                    message: response.data.message || "登录成功",
                    type: "success"
                  });

                  // 跳转到首页
                  this.$router.push('/shouye');
                } else {
                  // 登录失败
                  ElMessage({
                    showClose: true,
                    message: response.data.message || "登录失败",
                    type: "error"
                  });
                }
              })
              .catch(error => {
                console.error('登录请求失败:', error);

                // 根据错误类型提供更具体的错误信息
                let errorMessage = "登录请求失败，请稍后重试";

                if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_REFUSED') {
                  errorMessage = "无法连接到服务器，请确认服务器是否正常运行";
                } else if (error.response) {
                  // 服务器返回了错误状态码
                  errorMessage = `服务器错误 (${error.response.status}): ${error.response.data.message || '未知错误'}`;
                }

                ElMessage({
                  showClose: true,
                  message: errorMessage,
                  type: "error"
                });
              });
          } else {
            console.log("error submit!");
            ElMessage({
              showClose: true,
              message: "请检查输入框的内容",
              type: "error"
            });
            return false;
          }
        });
      } else {
        console.error("表单引用不存在");
      }
    },
  },
};
</script>

<style lang="scss">
.app_login {
  height: 100%;
  background-color: #2468f2;
  background-image: linear-gradient(to bottom right, #2468f2, #3478f2);
  display: flex;
  justify-content: center;
  align-items: center;

  .el-card {
    width: 400px;
    height: 300px;

    .card-header {
      text-align: center;
    }
  }
}

.el-input__validateIcon {
  color: green;
}
</style>
